// 账户体系模块处理函数

const utils = require("../../common/utils")
const svgCaptcha = require("svg-captcha")
// 密码加密模块
const bcrypt = require('bcryptjs')
// 引入邮箱服务
const transporter = require('../../config/smtp.js')
const server = require("../../server/admin/account")

// 注册
exports.register = async (req, res) => {
  const { email, password, qrcode } = req.body;
  await utils.verifyCode(email, qrcode, (err, isValid) => {
    if (err) return res.cc("redis出现错误")
    // 验证码正确
    if (!isValid) return res.cc("验证码错误或验证码已过期")
    server.register(email, password).then(result1 => {
      if (result1 == '邮箱已被注册') return res.cc(result1)
      return res.cc(result1, 200)
    }).catch(err => {
      return res.cc(err)
    })
  })
}

// 登录
exports.login = async (req, res) => {
  let { email, password, qrcode } = req.body
  if (!email || !password) return res.cc('邮箱或密码不合法')
  await utils.verifyCode('img', qrcode, (err, isValid) => {
    if (err) return res.cc("redis出现错误")
    // 验证码正确
    if (!isValid) return res.cc("验证码错误或验证码已过期")
    server.login(email, password).then(result => {
      return res.send({
        code: 200,
        message: '登录成功',
        data: result
      })
    }).catch(err => {
      return res.cc(err)
    })
  })
}

// 获取邮箱验证码
exports.qrECode = async (req, res) => {
  let email = req.body.email;
  if (!email) return res.cc('请输入邮箱')
  let qrcode = utils.randomNumber()
   transporter.sendMail({
     subject: '验证码',
     from: '1811082435@qq.com',
     to: email,
     text: `你好，你的验证码是：${qrcode}，请勿告知他人，以防个人信息泄露。`        
   }, async (err, msg) => {
     if (err) return res.cc(err)
     // 通过redis存储验证码
     await utils.storeVerificationCode(qrcode, email)
     return res.cc('验证码已发送', 200)
   })
}

// 获取图形验证码
exports.qrCode = async (req, res) => {
  const captcha = svgCaptcha.create({
    inverse: false,
    fontSize: 56,
    noise: 2,
    width: req.query.width || 150,
    height: req.query.height || 50,
    size: 4,
    ignoreChars: '0o1i',
    color: false,
    background: '#fff'
  })
  // 通过redis存储验证码
  await utils.storeVerificationCode(captcha.text)
  res.type('svg')
  res.send(captcha.data)
}

// 微信登录
exports.wxLogin = async (req, res) => {
  let { code, encryptedData, iv } = req.body
  server.wxLogin(code, encryptedData, iv).then(result => {
      return res.send({
        code: 200,
        message: '登录成功',
        data: result
      })
    }).catch(err => {
      return res.cc(err)
    })
}